package Java基础.JUC同步工具;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @DESC https://leetcode-cn.com/problems/print-in-order/
 * @Author tzq
 * @Date 2020-04-17 16:51
 **/
public class _1114_按序打印 {

    public static void main(String[] args) throws Exception {
        Foo foo = new Foo();


        Thread thread1 = new Thread(() -> {
            try {
                foo.first(() -> {
                    System.out.println("first");
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                foo.second(() -> {
                    System.out.println("second");
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        Thread thread3 = new Thread(() -> {
            try {
                foo.third(() -> {
                    System.out.println("third");
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        thread3.start();
        thread2.start();
        thread1.start();


    }


    static class Foo {
        private AtomicInteger first = new AtomicInteger();
        private AtomicInteger second = new AtomicInteger();
        public Foo() { }

        public void first(Runnable printFirst) {
            printFirst.run();
            first.incrementAndGet();
        }

        public void second(Runnable printSecond) {
            while (first.get() != 1) {
            }
            printSecond.run();
            second.incrementAndGet();
        }

        public void third(Runnable printThird) {
            while (second.get() != 1) {
            }
            printThird.run();
        }


    }
}
